package com.sam.im.heiqun.uis.activities;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.sam.im.heiqun.R;
import com.sam.im.heiqun.constant.Constant;
import com.sam.im.heiqun.entities.AddFriendEntity;
import com.sam.im.heiqun.entities.AddFriendResultEntivity;
import com.sam.im.heiqun.entities.Circlepreview;
import com.sam.im.heiqun.entities.ImFriendEntivity;
import com.sam.im.heiqun.entities.ImMessage;
import com.sam.im.heiqun.entities.MessageEntivity;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.entities.ValidateEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.uis.adapters.ChatRecyclerAdapter;
import com.sam.im.heiqun.uis.adapters.SendCircleAdapter;
import com.sam.im.heiqun.uis.dialogs.PopupWindowManages;
import com.sam.im.heiqun.utils.IMMessageToJson;
import com.sam.im.heiqun.utils.RxJavaUtil;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.google.gson.Gson;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.GlideUtils;
import com.yuyh.library.utils.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;

import com.sam.im.heiqun.utils.StringUtils;
import com.zq.utils.StringUtil;

/**
 * 好友详细
 */
public class FriendDetailActivity extends BaseSwipeBackActivity {

    String TAG = FriendDetailActivity.class.getSimpleName();
    @BindView(R.id.sure)
    Button sure;
    @BindView(R.id.delete)
    Button delete;
    @BindView(R.id.pre_v_back)
    ImageView pre_v_back;
    @BindView(R.id.img)
    ImageView img;
    @BindView(R.id.right)
    ImageView right;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.sex)
    TextView sex;
    @BindView(R.id.city)
    TextView city;
    @BindView(R.id.sign)
    TextView sign;
    @BindView(R.id.remark)
    TextView remark;
    @BindView(R.id.code_im)
    TextView code_im;
    @BindView(R.id.album)
    LinearLayout album;
    @BindView(R.id.img1)
    ImageView img1;
    @BindView(R.id.img2)
    ImageView img2;
    @BindView(R.id.img3)
    ImageView img3;
    @BindView(R.id.img_sex)
    ImageView img_sex;
    private SendCircleAdapter adapter;
    PGService mPgService;
    private boolean isMyFriend = false;//用于标识本地有用户数据，需要检测是否有修改
    private int receiveTip = 1;
    private Long uid;
    private int type = 0;//0-有多重状态进入的位置就是说有可能是好友，也有可能不是（搜索手机号用户，群成员列表点击，）;1-好友列表点击;2-新朋友申请;3-聊天点击头像;
    private ImFriendEntivity imFriendEntivityK;

    @Override
    public int getContentViewId() {
        return R.layout.activity_friend_detail;
    }

    @Override
    protected String getTitleText() {
        return getResources().getString(R.string.detail_data);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
//        EventBus.getDefault().register(this);//订阅
        mPgService = PGService.getInstance();
        type = getIntent().getIntExtra("type", 0);
        uid = getIntent().getLongExtra("id", 0);
        //Log.i(TAG, "details: getId==" + uid);
        Log.i("info", "uid==" + uid);
        if (0 != uid)
            imFriendEntivityK = ToolsUtils.getMyFriendForId(uid);
        if (imFriendEntivityK != null) {
            isMyFriend = true;
            setHeadView();
            setViewText();

        } else {
            isMyFriend = false;
            getUserById2("" + uid);
        }
        updateThisView();

        if ((uid + "").equals(ToolsUtils.getUser().getId() + "")) {
            sure.setVisibility(View.GONE);
            delete.setVisibility(View.GONE);
        }
        getcirclePics();
        //如果是黑群客服，详细资料右上角按钮隐藏
        if(null != imFriendEntivityK&&imFriendEntivityK.getId()==66666){
            right.setVisibility(View.INVISIBLE);
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (0 != uid) {
            imFriendEntivityK = ToolsUtils.getMyFriendForId(uid);
        }
        isMyFriend = imFriendEntivityK != null;
        if (isMyFriend) {
            setHeadView();
            setViewText();
        }
    }

    private void getcirclePics() {
        mPgService.getpreview(ToolsUtils.getMyUserId(), uid + "").subscribe(new AbsAPICallback<Circlepreview>() {
            @Override
            protected void onResultError(ApiException ex) {

            }

            @Override
            public void onNext(Circlepreview circlepreview) {
                if (circlepreview != null && !StringUtils.isEmpty(circlepreview.getAlbum())) {
                    String[] split = circlepreview.getAlbum().split(",");
                    for (int i = 0; i < split.length; i++) {
                        Log.i("info", " ");
                        if (i == 0) {
                            Glide.with(FriendDetailActivity.this).load(split[0]).placeholder(com.yuyh.library.R.drawable.loading).error(com.yuyh.library.R.drawable.loading).into(img1);
                        } else if (i == 1) {
                            GlideUtils.loadImage(FriendDetailActivity.this, split[1], img2);
                        } else if (i == 2) {
                            GlideUtils.loadImage(FriendDetailActivity.this, split[2], img3);
                        } else {
                            break;
                        }
                    }
                }
            }
        });
    }

    private void updateThisView() {
        switch (type) {
            case 0:
                if (isMyFriend) {
                    sure.setText(getString(R.string.send_message));
                    sure.setVisibility(View.VISIBLE);
                    right.setVisibility(View.VISIBLE);
                    right.setBackgroundResource(R.drawable.more_max);
                    delete.setVisibility(View.VISIBLE);
                } else {
                    sure.setText(getString(R.string.add_friend));
                    sure.setVisibility(View.VISIBLE);
                }
                break;
            case 1:
                sure.setText(getString(R.string.send_message));
                sure.setVisibility(View.VISIBLE);
                right.setVisibility(View.VISIBLE);
                right.setBackgroundResource(R.drawable.more_max);
                delete.setVisibility(View.VISIBLE);
                break;
            case 2:
                if (isMyFriend && ToolsUtils.isMyFriendForId(uid)) {
                    sure.setText(getString(R.string.send_message));
                    sure.setVisibility(View.VISIBLE);
                    right.setVisibility(View.VISIBLE);
                    right.setBackgroundResource(R.drawable.more_max);
                    delete.setVisibility(View.VISIBLE);
                } else {
                    sure.setText(getString(R.string.agree_));
                    sure.setVisibility(View.VISIBLE);
                }
                break;
            case 3:
//                sure.setVisibility(View.GONE);
//                right.setVisibility(View.GONE);
//                delete.setVisibility(View.GONE);
                sure.setText(getString(R.string.send_message));
                sure.setVisibility(View.VISIBLE);
                right.setVisibility(View.VISIBLE);
                right.setBackgroundResource(R.drawable.more_max);
                delete.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //好友解除了退出当前的聊天界面
    public void onFinish(String event) {
        if (event.equals(Constant.BYB_FRIEND)) {
            Toast.makeText(this, R.string.yout_friendship_already_finish, Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * @param destid
     */
    private void getUserById2(String destid) {
        Log.i(TAG, "getUserById2: ====================destid=" + destid);
        if (isMyFriend) {
            showProgress("");
        }
        String fromid = ToolsUtils.getMyUserId();
        mPgService.getUserById(fromid, destid).subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity mFriendEntivityg) {
                hideProgress();
                boolean isUpdate = false;
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=?", new String[]{ToolsUtils.getMyUserId() + "", uid + ""}, null, "time desc", null);

                MessageEntivity mMessageEntivity;
                if (isMyFriend) {
                    if (!mFriendEntivityg.getHeadUrl().equals(imFriendEntivityK.getHeadUrl())) {
                        isUpdate = true;
                        imFriendEntivityK.setHeadUrl(mFriendEntivityg.getHeadUrl());
                        imFriendEntivityK.save();
                        if (messageEntivities.size() > 0) {
                            mMessageEntivity = messageEntivities.get(0);
                            mMessageEntivity.setImgUrl(mFriendEntivityg.getHeadUrl());
                            mMessageEntivity.save();
                        }
                        setHeadView();//判断获取的新的用户信息头像是否改变
                    }
                    if (!mFriendEntivityg.getName().equals(imFriendEntivityK.getName())) {
                        isUpdate = true;
                        imFriendEntivityK.setName(mFriendEntivityg.getName());
                        imFriendEntivityK.save();
                        if (messageEntivities.size() > 0) {
                            mMessageEntivity = messageEntivities.get(0);
                            mMessageEntivity.setNick(mFriendEntivityg.getName());
                            mMessageEntivity.save();
                        }
                        setViewText();//判断获取的新的用户信息昵称是否改变
                    }
                    if (isUpdate) {
                        //刷新好友页面数据
                        EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                        /** 这里是获取好友信息，如果信息有修改通知会话列表页面更新，这里需要进入好友详情才会发送，不会大量发送 */
                        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                    }
                } else {
                    imFriendEntivityK = mFriendEntivityg;
                    setHeadView();
                    setViewText();
                }
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 设置用户头像
     */
    private void setHeadView() {
        String headUrl = imFriendEntivityK.getHeadUrl();
        GlideUtils.loadHeadCircularImage(getApplicationContext(), headUrl, img);
    }

    /**
     * 设置用户信息
     */
    private void setViewText() {
        String nameStr = imFriendEntivityK.getName();
        // name.setText(nameStr);
//        Log.i(TAG, "setViewText: ======"+new Gson().toJson(imFriendEntivityK));
//        Log.i(TAG, "setViewText: =====Sex="+imFriendEntivityK.getSex());
        if (getResources().getString(R.string.male).equals(imFriendEntivityK.getSex())) {
            img_sex.setImageResource(R.drawable.manimg);
            sex.setText(getResources().getString(R.string.male));
//        } else if (getResources().getString(R.string.female).equals(imFriendEntivityK.getSex())) {
        } else {
            img_sex.setImageResource(R.drawable.womenimg);
            sex.setText(getResources().getString(R.string.female));
        }
        city.setText(imFriendEntivityK.getProvince() + " " + imFriendEntivityK.getCity());
        if (imFriendEntivityK.getSign() != null && !StringUtils.isEmpty(imFriendEntivityK.getSign())) {
            sign.setText("" + imFriendEntivityK.getSign());
        }
        String remarkStr = imFriendEntivityK.getRemark();
        if (remarkStr == null || remarkStr.equals("")) {
            name.setText(nameStr);
            remark.setVisibility(View.GONE);
        } else {
            name.setText(remarkStr);
            remark.setText(getResources().getString(R.string.niname) + nameStr);
            remark.setVisibility(View.VISIBLE);
        }
//        String imno = imFriendEntivityK.getIMNo();
//        if (null!=imno&&imno.length()>0){
//            code_im.setText("IM："+imno);
//            code_im.setVisibility(View.VISIBLE);
//        }else{
//            code_im.setVisibility(View.GONE);
//        }
        code_im.setText("ID：" + imFriendEntivityK.getId());
        code_im.setVisibility(View.VISIBLE);

    }

    @OnClick({R.id.sure, R.id.right, R.id.pre_v_back, R.id.delete, R.id.img, R.id.album})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.album:
                Log.i("wgdinfo", "onClick: --------点击0003----------");
                if (isMyFriend && imFriendEntivityK != null) {
                    Log.i("wgdinfo", "onClick: --------点击0001----------uid=" + uid);
//                    Bundle bundle1 = new Bundle();
//                    bundle1.putString("frienid",  "");
//                    bundle1.putString("name", "");
//                    bundle1.putString("head", "");
//                    bundle1.putString("frienid", uid + "");
//                    bundle1.putString("name", imFriendEntivityK.getName());
//                    bundle1.putString("head", imFriendEntivityK.getHeadUrl());
//                    startActivity(MycircleActivty.class, bundle1);


                    Intent intent = new Intent(FriendDetailActivity.this, MycircleActivty.class);
                    intent.putExtra("frienid", uid + "");
                    intent.putExtra("name", imFriendEntivityK.getName());
                    intent.putExtra("head", imFriendEntivityK.getHeadUrl());
                    startActivity(intent);

                    //finish();
                } else if ((uid + "").equals(ToolsUtils.getUser().getId() + "")) {
                    Log.i("wgdinfo", "onClick: --------点击0002----------");
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("frienid", uid + "");
                    bundle1.putString("name", imFriendEntivityK.getName());
                    bundle1.putString("head", imFriendEntivityK.getHeadUrl());
                    startActivity(MycircleActivty.class, bundle1);
                } else {
                    ToolsUtils.showToast(FriendDetailActivity.this, getResources().getString(R.string.no_friend_not_look));
                }
                break;
            case R.id.pre_v_back:
                scrollToFinishActivity();
                break;
            case R.id.sure:
                if (type == 2) {
                    if (isMyFriend && ToolsUtils.isMyFriendForId(uid)) {
                        Bundle bundle = new Bundle();
                        bundle.putLong("destid", imFriendEntivityK.getId());
                        startActivityForResult(ChatActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
                        finish();
                    } else {
                        onAgreeNewFriendClick();
                    }
                } else {
                    if (type == 0) {
                        if (isMyFriend) {
                            Bundle bundle = new Bundle();
                            bundle.putLong("destid", imFriendEntivityK.getId());
                            startActivityForResult(ChatActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
                            finish();
                        } else {
                            addFriend();
                        }
                    } else {
                        Bundle bundle = new Bundle();
                        bundle.putLong("destid", imFriendEntivityK.getId());
                        startActivityForResult(ChatActivity.class, Constant.MESSAGE_MAIN_GO_GROUP_RESULT, bundle);
                        finish();
                    }
                }
                break;
            case R.id.right:
                List<String> mStrs = new ArrayList<>();
                mStrs.add(getResources().getString(R.string.add_black_list));//加入黑名单
//                mStrs.add("消息免打扰");
                mStrs.add(getResources().getString(R.string.alter_remark));//修改备注

                mStrs.add(getResources().getString(R.string.set_circle_qx));//设置朋友圈权限

                mStrs.add(getResources().getString(R.string.complaint));//投诉

                mStrs.add(getResources().getString(R.string.send_this_mp));//发送该名片
                PopupWindowManages.initListSelect(getApplicationContext(), view, mStrs, new PopupWindowManages.OnPopSelectIdStr() {
                    @Override
                    public void onOkClick(int whichButton, String content) {
                        switch (whichButton) {
                            case 0://加入黑名单
                                setBlock("" + uid, ToolsUtils.getMyUserId());
                                break;
                            case 1://修改备注名
                                Bundle bundle = new Bundle();
                                bundle.putString("destid", uid + "");
                                bundle.putString("remark", name.getText().toString() + "");
                                FriendDetailActivity.this.startActivity(AlterRemarkActivity.class, bundle);
                                break;
                            case 2://设置朋友圈权限
                                SetCircleComplaintActivity.start(FriendDetailActivity.this, "" + uid);
                                break;
                            case 3://投诉
                                MyWebViewManageActivity.start(FriendDetailActivity.this, 3, "http://samim.huiwork.com/wap/reportFriend", "" + uid, 1);
//                                showToast("正在开发中...");
                                break;
                            case 4://发送该名片
                                showToast(getResources().getString(R.string.now_working));
                                break;
                        }
                    }
                });
                break;
            case R.id.delete:
                //delFriend("" + uid);
                if(imFriendEntivityK.getId()==66666){
                    showToast("黑群客服不允许删除");
                    return;
                }
                ExitDialog dialog = new ExitDialog(FriendDetailActivity.this);
                dialog.show();
                dialog.setmOnDialogSelect(new ExitDialog.OnDialogSelect() {
                    @Override
                    public void btnConfirm() {
                        delFriend("" + uid);
                    }

                    @Override
                    public void btnCancel() {

                    }
                });

                break;
            case R.id.img:
                if (null != imFriendEntivityK) {
                    ArrayList<String> imageList = new ArrayList<>();
                    imageList.add(imFriendEntivityK.getHeadUrl());
                    Intent intent = new Intent(getApplicationContext(), ImageViewActivity.class);
                    intent.putStringArrayListExtra("images", imageList);
                    intent.putExtra("clickedIndex", 0);
                    startActivity(intent);
                }
                break;
        }
    }

    private void onAgreeNewFriendClick() {
        showProgress(getString(R.string.commiting));
        final UserEntivity userEntivity = ToolsUtils.getUser();
        mPgService.acceptRequest("" + uid,
                imFriendEntivityK == null || "0".equals(imFriendEntivityK.getIsFriend()) ? "1" : "1",
                null,
                null,
                userEntivity.getId() + "").subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(getResources().getString(R.string.add_defeat));
                hideProgress();
            }

            @Override
            public void onNext(ImFriendEntivity entivity) {

                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=? and from_type=?",
                        new String[]{userEntivity.getId() + "", entivity.getId() + "", Constant.FROM_TYPE_SYS + ""});
                if (messageEntivities.size() > 0) {
                    MessageEntivity messageEntivity = messageEntivities.get(0);
                    messageEntivity.setMessageNum(0);
                    messageEntivity.save();
                }
                /** 同意好友申请通知刷新界面，这里不会大量发送*/
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);//通知刷新界面
                //添加本地好友数据
                if (!ToolsUtils.isMyFriendForId(entivity.getId())) {
                    getUserById(entivity.getId() + "");
                }
            }
        });
    }


    void addFriend() {

        View view = LayoutInflater.from(FriendDetailActivity.this).inflate(R.layout.dialog_send_friend_request, null);
        final EditText editText = view.findViewById(R.id.et_send_content);
        editText.setHint(StringUtil.format(FriendDetailActivity.this, R.string.hello_i_am, ToolsUtils.getUser().getName()));
        AlertDialog alertDialog = new AlertDialog.Builder(FriendDetailActivity.this)
                .setTitle(R.string.verify_apply)
                .setMessage(R.string.verify_apply_content)
                .setView(view)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        String string = editText.getText().toString();
                        if (TextUtils.isEmpty(string)) {
                            string = editText.getHint().toString();
                        }
                        requestFriend(string);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .create();
        alertDialog.show();
    }


    /**
     * 添加好友
     */
    private void requestFriend(String string) {
        showProgress(null);
//        Log.i(TAG, "添加好友requestFriend: destId = " + mFriendEntivity.getId() + "--myId = " + ToolsUtils.getMyUserId());
        PGService.getInstance().getNetApi().requestFriend("1", "" + uid, ToolsUtils.getMyUserId(), string)
                .compose(RxJavaUtil.<AddFriendEntity>applySchedules())
                .compose(this.<AddFriendEntity>bindLifeCycle())
                .subscribe(new AbsAPICallback<AddFriendEntity>() {

                    @Override
                    public void onNext(AddFriendEntity addFriendEntity) {
                        hideProgress();
                        /** 加好友使用，不会大量发送 */
                        EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);//通知刷新界面
                        showToast(getResources().getString(R.string.friend_apply_already_commit));
                        scrollToFinishActivity();
                    }

                    @Override
                    protected void onResultError(ApiException ex) {
                        hideProgress();
                        try {
                            /*{"code":"2","data":"{\"info\":\"完成 \"}"}*/
                            AddFriendResultEntivity resultModel = new Gson().fromJson(ex.getDisplayMessage(), AddFriendResultEntivity.class);
                            if ("2".equals(resultModel.getCode())) {
                                getUserById(uid + "");
                            }
                        } catch (Exception e) {
                            showToast(getResources().getString(R.string.friend_apply_already_commitno));
                        }
                        Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
                    }
                });
    }


    /**
     * 根据好id查询详情（此处用于添加好友），查询完成后保存数据库
     *
     * @param destid
     */
    private synchronized void getUserById(final String destid) {

        final String fromid = ToolsUtils.getMyUserId();

        mPgService.getUserById(fromid, destid).subscribe(new AbsAPICallback<ImFriendEntivity>() {
            @Override
            public void onNext(ImFriendEntivity mFriendEntivity) {

                UserEntivity userEntivity = ToolsUtils.getUser();
                //更新数据库
                mFriendEntivity.setCurrentid(userEntivity.getId());
                mFriendEntivity.setIsBlack("0");
                mFriendEntivity.save();
                mFriendEntivity.setId(mFriendEntivity.getId());
                mFriendEntivity.save();

                //插入一条提示开始聊天的消息
                ImMessage localImMessage = new ImMessage();
                localImMessage.setFromid(mFriendEntivity.getCurrentid());
                localImMessage.setFromname(mFriendEntivity.getName());
                localImMessage.setImageIconUrl(mFriendEntivity.getHeadUrl());
                localImMessage.setDestid(mFriendEntivity.getId());
                localImMessage.setFromType(1);
                localImMessage.setVersion(1);
                localImMessage.setSendTime(System.currentTimeMillis());
                localImMessage.setReceiveTime(localImMessage.getSendTime());
                localImMessage.setDevType(1);
                localImMessage.setMessageType(Constant.MESSAGE_TYPE_AGREE_FRIEND_APPLY);
                localImMessage.setType(ChatRecyclerAdapter.SHOW_AGREE_FRIEND_REQUEST);
                localImMessage.setMsgId(String.valueOf(System.currentTimeMillis()));
                localImMessage.setContent(StringUtil.format(FriendDetailActivity.this, R.string.agree_friend_apply_can_chat, localImMessage.getFromname()));
                localImMessage.setUniqueness(localImMessage.getFromid() + "_" + localImMessage.getDestid());
                EventBus.getDefault().post(localImMessage);

                MessageEntivity messageEntivity = IMMessageToJson.ImMessageToMessageEntivity(localImMessage, Constant.FROM_TYPE_OTHER);
                localImMessage.save();//存储接受的数据
                if (messageEntivity != null) {
                    EventBus.getDefault().post(messageEntivity);
                } else {
                    EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                }


                //刷新好友页面数据
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                showToast(getResources().getString(R.string.add_success));
                if (type == 2) {//返回到mian
                    Intent intent = new Intent(FriendDetailActivity.this, MainActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                } else {
                    scrollToFinishActivity();
                }
            }

            @Override
            protected void onResultError(ApiException ex) {
//                showToast(ex.getDisplayMessage());
                //  Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    @Override
    protected void onDestroy() {
//        EventBus.getDefault().unregister(this);

        super.onDestroy();
    }

    /**
     * 设置黑名单
     *
     * @param fromid
     * @param destid
     */
    private void setBlock(final String destid, final String fromid) {
        mPgService.setBlock(destid, fromid).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            public void onNext(ValidateEntivity friendEntivity) {
                showToast(getResources().getString(R.string.add_black_list_success));
//                scrollToFinishActivity();
                List<MessageEntivity> messageEntivities = MessageEntivity.find(MessageEntivity.class, "fromid=? and destid=? and uniqueness=?", fromid, destid, "_");
                if (messageEntivities.size() > 0) {
                    messageEntivities.get(0).delete();//删除消息列表
                }
                ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, uid);
                imFriendEntivity.setIsBlack(Constant.IS_BLACK);
                imFriendEntivity.save();

                EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
                /** 拉黑好友使用，不会大量发送 */
                EventBus.getDefault().post(Constant.MAIN_BOTTOM_TIP_NUM);
                scrollToFinishActivity();
            }

            @Override
            protected void onResultError(ApiException ex) {
                Log.i("-----", "--001ex.getDisplayMessage()--" + ex.getDisplayMessage());
            }
        });
    }

    /**
     * 删除好友
     *
     * @param uIdt
     */
    public void delFriend(final String uIdt) {
        mPgService.delFriend(uIdt, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<ValidateEntivity>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(ex.getDisplayMessage());
            }

            @Override
            public void onNext(ValidateEntivity data) {//好友删除成功

                //删除数据库
                ImFriendEntivity imFriendEntivity = ImFriendEntivity.findById(ImFriendEntivity.class, Long.parseLong(uIdt));
                if (imFriendEntivity != null) {
                    imFriendEntivity.delete();
                }

                MessageEntivity messageEntivity = new MessageEntivity();
                messageEntivity.setFromType(Constant.BLACK_BROADCAST_MESSAGE_REFRESH);
                messageEntivity.setDestid(Long.parseLong(uIdt));
                try {
                    long fromid = Long.parseLong(ToolsUtils.getMyUserId());
                    messageEntivity.setFromid(fromid);
                    //清空数据库
                    ImMessage.deleteAll(ImMessage.class, "uniqueness=?", new String[]{fromid + "_" + uIdt});
                } catch (Exception e) {

                }
                EventBus.getDefault().post(messageEntivity);
                new ToastUtils().showSingleToast(data.getInfo());

                EventBus.getDefault().post(Constant.BLACK_BROADCAST_FOUND_REFRESH);
                EventBus.getDefault().post(Constant.BLACK_BROADCAST_ADD_GROUP_FOUND_REFRESH);
                scrollToFinishActivity();
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void changeData(ImFriendEntivity imFriendEntivity) {
        name.setVisibility(View.VISIBLE);
        name.setText(imFriendEntivity.getRemark());
        remark.setText(getResources().getString(R.string.niname) + imFriendEntivity.getName());
        remark.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Constant.MESSAGE_MAIN_GO_GROUP_RESULT:
                Log.i("wgdinfo", "onActivityResult: -------这里？-----");
                if (resultCode == Constant.MESSAGE_MAIN_GO_GROUP_RESULT) {
                    setResult(Constant.MESSAGE_MAIN_GO_GROUP_RESULT);
                    scrollToFinishActivity();
                }
                break;
        }
    }

}
